/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.mongodb.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory;

import com.foreveross.bsl.mongodb.repository.handler.MultRouterScheme;
import com.foreveross.bsl.mongodb.repository.handler.RouterScheme;
import com.foreveross.bsl.mongodb.repository.handler.SimpleRouterScheme;
import com.foreveross.bsl.mongodb.repository.router.RouterMongodbFactory;


/**
 * @description
 *
 * @author rening
 * @version v1.0
 *
 * @2013-5-31
 *
 */
public class MongodbFactoryConfig {
	
	private @Autowired MongodbConfig config;

	
	public @Bean(name = "mongoDbFactory") MongoDbFactory mongoDbFactory() throws Exception {
		RouterMongodbFactory factory;
		if(config.getUsername() != null && !"".equals(config.getUsername())){
			UserCredentials userCredentials = new UserCredentials(config.getUsername(), config.getPassword());
			factory = new RouterMongodbFactory(config.mongo(), config.getDefaultDatabase(), userCredentials);
			factory.setRouterScheme(getRouterScheme(factory, userCredentials));
		} else { // mongodb 不加密情况
			factory = new RouterMongodbFactory(config.mongo(), config.getDefaultDatabase());
			factory.setRouterScheme(this.getRouterScheme(factory, UserCredentials.NO_CREDENTIALS));
		}
		return factory;
	}
	
	private RouterScheme getRouterScheme(RouterMongodbFactory factory, UserCredentials userCredentials) {
		if(config.getMultiDatabase() != null &&"true".equals(config.getMultiDatabase().toLowerCase())) {
			MultRouterScheme routerScheme = new MultRouterScheme(userCredentials, factory);
			routerScheme.setGlobalDatabasePackage(config.getGlobalDatabasePackage());
			return routerScheme;
		} else {
			SimpleRouterScheme routerScheme = new SimpleRouterScheme(userCredentials, factory);
			routerScheme.setGlobalDatabasePackage(config.getGlobalDatabasePackage());
			return routerScheme;
		}
	}
}
